package com.glitter.player.springbootdatasource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@SpringBootApplication
@Slf4j
public class SpringbootDatasourceApplication implements CommandLineRunner {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public static void main(String[] args) {
        SpringApplication.run(SpringbootDatasourceApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        showConnectionInfo();
        showData();
    }

    /*获取连接并且打印出来*/
    private void showConnectionInfo() throws SQLException {
        log.info("数据源:{}",dataSource.toString());
        Connection connection=dataSource.getConnection();
        log.info("连接信息:{}",connection.toString());
        connection.close();
    }

    /*查询GLITTER中的所有信息并打印出来*/
    private void showData(){
        jdbcTemplate.queryForList("SELECT * FROM GLITTER")
                .forEach(row->log.info(row.toString()));
    }
}
